// pages/shopping-mall/shopping-mall.js
var app = getApp();
var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var page = 1;
var loadingMore = false;
var hasMore = true;
// var localType = [{ cname: "推荐", zhiding: "1", goods_id: 'ding' }, { cname: "新品", num: "30", goods_id: 'new' }];
var dataall;
var allGoodsData = {};
var wxAuthFail = true;
var price = 0;
var hot = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    util: util,
    tc: 0,

    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    uid: '',
    token: '',
    userinfo: '',
    catadata: [],
    currcata: 0,
    selectCata: {},
    goodTypeName: '',

    infodata: [],
    goodsList: [],

    content_w: 240,
    goodTypeView_w: 80,


    noData: false,

    canEdit: false,

    searchVal: '',
    toporder: '1',

    priceorder: 0,
    hotorder: 0,

    nowcata: '',
    hidecata: true,

    colorSet: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var tc = app.get_tc();
    var that = this;
    that.setData({
      tc: tc,
    });
    wx.showLoading({
      title: tc == 1 ? '加載中' : '加载中',
      mask: 'true'
    });

    if (util.orgid == 14148) {
      var titlename = tc == 1 ? '報名' : '报名';
    } else {
      var titlename = tc == 1 ? '產品' : '产品';
    }

    wx.setNavigationBarTitle({
      title: titlename,
    })
    // var that = this;
    wx.getSystemInfo({
      success: function(res) {

        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          isIphone_x: isIphone_x,
          content_w: res.windowWidth - 78,
          goodTypeView_w: (res.windowWidth - 78) / 3
        });
      }
    })
    //获取颜色配置
    app.getColorSetData(function(color) {
      var col = color.shop_col ? parseInt(color.shop_col) : 2;
      col = col > 0 ? col : 2;
      that.setData({
        colorSet: color,
        content_item_w: (that.data.content_w - (col + 1) * 5) / col
      })
      that.resetNavColor();
    });
    //初始化底部导航
    var b_nav_data = app.getBottomNavData('shopping-mall/shopping-mall', function(data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
        tc: tc
      });
    });

    allGoodsData = {};



    var inviteuid = options.inviteuid;
    util.api({
      data: {
        "tc": that.data.tc,
        "publickey": util.publiccode,
        "ac": "goodstype"
      },
      success: function(responseData) {
        console.log("goodstype", responseData.data);
        var goodsType = responseData.data;
        if (!goodsType.msg) {
          dataall = goodsType
          that.setData({
            catadata: dataall,
            selectCata: dataall[0],
            nowcata: dataall[0].child
          });
          that.loadGoodsListData(1);
        } else {
          wx.hideLoading();
        }
      }
    });

    //读取登录用户信息
    app.LoginUserInfo(function(res) {
      if (res && res != -1) {
        that.setData({
          uid: res.uid,
          token: res.token,
          userinfo: res,
        });
        // that.getEditAuth();
      }
    }, '');
  },

  //获取当前登录用户是否有权限编辑该数据
  getEditAuth: function() {
    var that = this;
    var params = {
      "publickey": util.publiccode,
      "ac": "adminuser"
    };
    console.log("获取管理组人员id参数：", params);
    util.api({
      data: params,
      success: function(responseData) {
        console.log("获取管理组人员数据：", responseData);
        if (responseData.data.res) {
          var authUsers = responseData.data.mauid.split(',');
          if (that.data.uid) {
            for (var i = 0; i < authUsers.length; i++) {
              if (that.data.uid == authUsers[i]) {
                that.setData({
                  canEdit: true
                });
                break;
              }
            }
          }
        }
      }
    });
  },

  changeCata: function(event) {
    if (loadingMore) {
      return false;
    }

    price = 0;
    hot = 0;
    var that = this;
    var cataid = event.currentTarget.dataset.cataid;
    var cataindex = event.currentTarget.dataset.index;
    console.log(cataid, cataindex);
    page = 1;
    hasMore = true;
    loadingMore = false;
    that.setData({
      // infodata: dataall[cataindex]['child'] ? dataall[cataindex]['child'] : [],
      selectCata: dataall[cataindex],
      currcata: cataindex,
      nowcata: dataall[cataindex].child,
      searchVal: '',
      toporder: '1',
      hidecata: true,
      priceorder: 0,
      hotorder: 0,
      goodTypeName: '',
      noData: false
    });
    var goodsTypeId = that.data.selectCata.goods_id;
    var data = allGoodsData[goodsTypeId];
    console.log("goodsType = " + goodsTypeId + "; data = " + data);
    if (data && data.length > 0) {
      that.setData({
        goodsList: data,
      });
    } else {
      wx.showLoading({
        title: that.data.tc == 1 ? '加載中' : '加载中',
        mask: 'true'
      })
      that.loadGoodsListData(1);
    }
  },

  loadMore: function() {
    if (!loadingMore && hasMore) {
      page++;
      if (this.data.searchVal && this.data.searchVal.length > 0) {
        this.search();
      } else {
        this.loadGoodsListData(page);
      }
    }
  },

  loadGoodsListData: function(cpage) {
    var that = this;
    var goodsTypeId = that.data.selectCata.goods_id;
    if (goodsTypeId == 'new' && cpage > 1) {
      console.log("这个不用下拉刷新");
      wx.hideLoading();
      return false;
    }

    loadingMore = true;
    var gtype = goodsTypeId;
    if (goodsTypeId == 'new' || goodsTypeId == 'ding') {
      gtype = '';
    }

    var zhiding = that.data.selectCata.zhiding ? that.data.selectCata.zhiding : '';
    var num = that.data.selectCata.num ? that.data.selectCata.num : '10';
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '4',
      orgid: util.orgid,
      toporder: that.data.toporder,
      zhiding: zhiding,
      page: cpage.toString(),
      gtype: gtype,
      sellprice: price,
      hot: hot,
      num: num
    };

    console.log("商店商品请求参数：", params);
    util.api({
      data: params,
      success: function(responseData) {
        console.log("商店商品数据:", responseData);
        var resData = responseData.data;
        var newData = '';
        if (resData.msg) {
          hasMore = false;
          if (cpage <= 1) {
            that.setData({
              goodsList: [],
            });
          };
        } else {
          if (cpage > 1) {
            newData = that.data.goodsList.concat(resData);
          } else {
            newData = resData;
          };
          that.setData({
            goodsList: newData,
          });
          allGoodsData[goodsTypeId] = newData;
          console.log("allGoodsData:", allGoodsData);
        }
        loadingMore = false;
        if (cpage <= 1 && that.data.goodsList.length <= 0) {
          that.setData({
            noData: true
          });
        };

        wx.hideLoading();
      }
    });
  },

  inputVal: function(e) {
    this.setData({
      searchVal: e.detail.value
    })
  },

  searchAction: function() {
    this.setData({
      hidecata: true
    })
    if (this.data.searchVal && this.data.searchVal.length > 0) {
      hasMore = true;
      loadingMore = false;
      page = 1;
      this.setData({
        noData: false
      });
      this.search();
    }
  },

  search: function() {
    wx: wx.showLoading({
      title: 'loading',
      mask: true,
    });
    loadingMore = true;
    var that = this;
    var source = this.data.source;
    var params = {
      publickey: util.publiccode,
      ac: "search",
      topictype: 4,
      keyword: that.data.searchVal,
      type: 1,
      page: page,
      num: that.data.limit
      // groupsel: 1
    };
    console.log("search请求参数：", params);
    util.api({
      data: params,
      success: function(responseData) {
        console.log(responseData);
        var resData = responseData.data;
        var newData;
        if (resData.msg) {
          hasMore = false;
          if (page <= 1) {
            that.setData({
              goodsList: [],
            });
          }
          var titlename = that.data.tc == 1 ? '沒有符合條件的數據' : '没有符合条件的数据';
          wx.showToast({
            title: titlename,
          })
        } else {
          if (page <= 1) {

            that.setData({
              goodsList: resData,
            });
          } else {
            newData = that.data.searchResult.concat(resData);
            that.setData({
              goodsList: newData,
            });
          }

        }
        loadingMore = false;
        if (page <= 1 && that.data.goodsList.length <= 0) {
          that.setData({
            noData: true
          });
        };
        wx: wx.hideLoading();
      }
    });
  },

  showType: function(event) {
    var that = this;
    this.setData({
      hidecata: !that.data.hidecata
    })
  },

  selectGoodsType: function(e) {
    hot = 0;
    price = 0;
    page = 1;
    var goodsType = e.currentTarget.dataset.type;
    this.setData({
      selectCata: goodsType,
      goodTypeName: goodsType.cname,
      toporder: 1,
      hidecata: true,
      noData: false
    });
    this.loadGoodsListData(1);
  },

  priceOrder: function() {
    hot = 0;
    page = 1;
    if (price == 0 || price == 1) {
      price = 2;
    } else {
      price = 1;
    }
    this.setData({
      hotOrder: hot,
      priceOrder: price,
      toporder: '',
      // goodTypeName: '',
      hidecata: true
    });
    this.loadGoodsListData(1);
  },
  hotOrder: function() {
    price = 0;
    page = 1;
    if (hot == 0 || hot == 1) {
      hot = 2;
    } else {
      hot = 1;
    }
    this.setData({
      hotOrder: hot,
      priceOrder: price,
      // goodTypeName: '',
      toporder: '',
      hidecata: true
    });
    this.loadGoodsListData(1);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  //页面分享
  onShareAppMessage: function() {
    var that = this;
    var inviteuid = that.data.loginuid ? that.data.loginuid : '';
    console.log("分享id" + inviteuid);

    return {
      title: that.data.org_name,
      path: '/pages/index/index?&inviteuid=' + inviteuid
    };
  },


  showEWM: function(e) {
    var shareImgUrl = e.currentTarget.dataset.imgsrc;
    console.log("图片链接：" + shareImgUrl);
    wx.previewImage({
      current: shareImgUrl,
      urls: [shareImgUrl]
    })
  },


  goAtherPageRedirect: function(e) {
    var url = e.currentTarget.dataset.link;
    if (url) {
      wx.redirectTo({
        url: url
      });
    }
  },
  goAtherPage: function(e) {
    var url = e.currentTarget.dataset.link;
    if (url) {
      wx.navigateTo({
        url: url
      });
    }
  },

  //保存formId
  submitFormId: function(e) {
    app.saveFormId(e.detail.formId);

    var path = e.detail.value.nav_path;
    if (path && path.indexOf('navto:') == 0) {
      var navPath = path.slice(6);
      wx.navigateTo({
        url: navPath,
      })
    } else {
      wx.redirectTo({
        url: path
      });
    }
  },
  resetNavColor: function() {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },
})